// app.js
App({
  onLaunch() {
    // 初始化本地存储
    this.initStorage();
    
    // 检查是否授权通知
    this.checkNotificationPermission();
    
    // 初始化提醒服务
    this.initReminderService();
  },
  
  initStorage() {
    // 检查是否有初始化数据
    if (!wx.getStorageSync('bloodPressureRecords')) {
      wx.setStorageSync('bloodPressureRecords', []);
    }
    
    if (!wx.getStorageSync('medicationRecords')) {
      wx.setStorageSync('medicationRecords', []);
    }
    
    if (!wx.getStorageSync('settings')) {
      wx.setStorageSync('settings', {
        reminderTime: '08:00',
        medicationName: '降压药',
        unit: 'mmHg',
        userName: '',
        age: '',
        gender: ''
      });
    }
  },
  
  checkNotificationPermission() {
    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.notification']) {
          wx.authorize({
            scope: 'scope.notification',
            success() {
              console.log('通知授权成功');
            },
            fail() {
              console.log('通知授权失败');
              wx.showToast({
                title: '请开启通知权限以接收用药提醒',
                icon: 'none',
                duration: 3000
              });
            }
          });
        }
      }
    });
  },
  
  initReminderService() {
    const settings = wx.getStorageSync('settings');
    if (settings.reminderTime) {
      this.setReminder(settings.reminderTime);
    }
  },
  
  setReminder(time) {
    // 取消之前的提醒
    wx.removeStorageSync('reminderTimer');
    
    // 解析目标时间
    const [targetHour, targetMinute] = time.split(':').map(Number);
    
    // 设置每日提醒
    const now = new Date();
    const targetTime = new Date(
      now.getFullYear(),
      now.getMonth(),
      now.getDate(),
      targetHour,
      targetMinute
    );
    
    // 如果目标时间已过，设置明天的提醒
    if (targetTime < now) {
      targetTime.setDate(targetTime.getDate() + 1);
    }
    
    const delay = targetTime - now;
    
    // 设置定时器
    const timer = setTimeout(() => {
      this.sendReminder();
      // 设置下一天的提醒
      this.setReminder(time);
    }, delay);
    
    wx.setStorageSync('reminderTimer', timer);
  },
  
  sendReminder() {
    // 发送本地通知
    wx.showNotification({
      title: '用药提醒',
      content: '该吃药了，请记录您的用药情况',
      success: () => {
        // 打开用药记录页面
        wx.navigateTo({
          url: '/pages/medication/medication'
        });
      }
    });
    
    // 15分钟后检查是否已记录
    setTimeout(() => {
      this.checkMedicationRecord();
    }, 15 * 60 * 1000);
  },
  
  checkMedicationRecord() {
    const records = wx.getStorageSync('medicationRecords');
    const today = new Date().toISOString().split('T')[0];
    
    // 检查今天是否有用药记录
    const hasRecordToday = records.some(record => 
      record.recordTime.startsWith(today)
    );
    
    if (!hasRecordToday) {
      // 15分钟内未记录，再次提醒
      wx.showNotification({
        title: '用药提醒',
        content: '您还没有记录今天的用药情况，请及时记录',
        success: () => {
          wx.navigateTo({
            url: '/pages/medication/medication'
          });
        }
      });
    }
  },
  
  globalData: {
    userInfo: null
  }
})